/*
 * Copyright (C) 2012 Le Tuan Anh <anh.takaji@gmail.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package ezcms.dal.hibernate.mysql;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

/**
 * Hibernate Factory
 *
 * @author Le Tuan Anh <anh.takaji@gmail.com>
 */
public class HibernateFactory {

    private static SessionFactory sessionFactory;

    public static Session openSession() throws HibernateException {
        buildIfNeeded();
        return sessionFactory.openSession();
    }

    public static SessionFactory buildIfNeeded() throws HibernateException {
        if (sessionFactory != null) {
            return sessionFactory;
        }
        return configureSessionFactory();
    }

    private static SessionFactory configureSessionFactory() throws HibernateException {
        Configuration configuration = new Configuration().configure();
        sessionFactory = configuration.buildSessionFactory();
        return sessionFactory;
    }

    public static void close(Session session) {
        if (session != null) {
            try {
                session.clear();
                session.flush();

            } catch (Exception ignored) {
                //TODO: Log error?
            }
            try {
                session.close();
            } catch (Exception ex) {
            }
        }
    }

    public static void rollback(Transaction tx) {
        try {
            if (tx != null) {
                tx.rollback();
            }
        } catch (Exception ex) {
            //TODO: Log error?
        }
    }
}
